package com.example.nonggo.utils;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ActivityManager implements Application.ActivityLifecycleCallbacks {
    private static final List<Activity> activityList = new ArrayList<>();

    public static void addActivity(Activity activity) {
        activityList.add(activity);
    }

    public static void removeActivity(Activity activity) {
        activityList.remove(activity);
    }

    /**
     * 关闭所有Activity
     *
     * @param activities 排除的Activity
     */
    public static void finishAll(Activity... activities) {
        List<Activity> otherActivities = new ArrayList<>();
        if (activities != null) {
            otherActivities.addAll(Arrays.asList(activities));
        }
        for (Activity activity : activityList) {
            if (!activity.isFinishing() && !otherActivities.contains(activity)) {
                activity.finish();
            }
        }
        activityList.clear();
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        activityList.add(activity);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        activityList.remove(activity);
    }
}

